﻿using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Services;
using Sunny.UI;
using static CoreShop.Library.GlobalEnumVars;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Diagnostics;
using System.Windows.Forms;
using System.Collections.Generic;
using SqlSugar.Extensions;
using System;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using SqlSugar;

namespace CoreShop.App
{
    public partial class frmPrintSchemeInfo : UIForm
    {
        corecmsprintscheme printscheme = new corecmsprintscheme();
        List<corecmsprintbilltype> printbilltypes = new List<corecmsprintbilltype>();
        public frmPrintSchemeInfo(corecmsprintscheme _cheme)
        {
            InitializeComponent();
            printscheme = _cheme;
        }

        public frmPrintSchemeInfo()
        {
        }

        private void frmPrintSchemeInfo_Load(object sender, System.EventArgs e)
        {
            GetPrinter();
            BindComboBoxData();
            LoadBillType(printscheme.printerType);
            ControlsDataBinding.DataBind(printscheme, this, DataSourceUpdateMode.OnPropertyChanged);
            try
            {
                printerType.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.printerType>(printscheme.printerType.ObjToInt(0));
                brandId.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.PrinterBrand>(printscheme.brandId.ObjToInt(0));
                sendPrintWay.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.SendPrintWay>(printscheme.sendPrintWay.ObjToInt(0));
                paperType.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.paperType>(printscheme.paperType.ObjToInt(0));
                printConnect.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.printConnect>(printscheme.printConnect.ObjToInt(0));
                if (printscheme != null)
                {
                    this.buzzingCount.Value = printscheme.buzzingCount;
                    this.buzzingType.Value = printscheme.buzzingType;
                    this.emptyRows.Value = printscheme.emptyRows;
                    if (printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command)
                        printerName.DropDownStyle = UIDropDownStyle.DropDown;
                    else
                        printerName.DropDownStyle = UIDropDownStyle.DropDownList;
                    printerName.Text = printscheme.printerName;
                    printerType.SelectedValue = printscheme.printerType;
                    paperType.SelectedValue = printscheme.paperType;
                    sendPrintWay.SelectedValue = printscheme.sendPrintWay;
                    spareSchemeId.SelectedValue = printscheme.spareSchemeId;                    
                    status.SelectedValue = printscheme.status;
                    this.address.Text = printscheme.address;
                    this.linkPhone.Text = printscheme.linkPhone;
                    retryCount.SelectedValue = printscheme.retryCount;
                }
            }
            catch { }
        }

        private void LoadBillType(int printerType)
        {
            var schemeDetails = new corecmsprintschemedetailServices().QueryByPrintSchemeId(printscheme.id);
            printbilltypes = new corecmsprintbilltypeServices().AsQueryable().Where(p => p.tagId == printerType).ToList();
            mbtBillTypes.Clear();
            mbtBillTypes.MaxSelected = printbilltypes.Count;
            foreach (var item in printbilltypes)
            {
                bool selectFlag = false;
                var schemeDetail = schemeDetails.Find(p => p.billtypeId == item.id && p.selectedFlag == true);
                if (schemeDetail != null) selectFlag = true;
                if ((!selectFlag) && (printscheme.id.ObjToInt() == 0) && (printscheme.printerType == (int)GlobalEnumVars.printerType.PosBill))
                {
                    selectFlag = true;
                }
                mbtBillTypes.Add(item.name, item.id, selectFlag);
            }
            if (printerType == (int)GlobalEnumVars.printerType.Kitchen)
            {
                sendPrintWay.Enabled = true;
            }
            else
            {
                sendPrintWay.SelectedValue = (int)GlobalEnumVars.SendPrintWay.Drive;
                sendPrintWay.Enabled = false;
            }
        }

        private void GetPrinter()
        {
            try
            {
                printerName.Items.Clear();
                printerName.Items.Add(GlobalConstVars.defaultPrinter);

                System.Drawing.Printing.PrintDocument print = new System.Drawing.Printing.PrintDocument();
                foreach (string sPrint in System.Drawing.Printing.PrinterSettings.InstalledPrinters)//获取所有打印机名称
                {
                    printerName.Items.Add(sPrint);
                }
                string sDefault = print.PrinterSettings.PrinterName;//默认打印机名
                printerName.Text = print.PrinterSettings.PrinterName;
            }
            catch
            {
            }
        }

        public void BindComboBoxData()
        {
            try
            {
                #region 加载打印机类型
                //printerType.Enabled = false;
                this.printerType.Items.Clear();
                var printTypeList = EnumHelper.EnumToList<GlobalEnumVars.printerType>();
                printerType.DataSource = printTypeList;
                printerType.DisplayMember = "description";
                printerType.ValueMember = "value";
                //printerType.Enabled = true;
                #endregion

                #region 加载打印机品牌
                this.brandId.Items.Clear();
                var brandList = EnumHelper.EnumToList<GlobalEnumVars.PrinterBrand>();
                brandId.DataSource = brandList;
                brandId.DisplayMember = "description";
                brandId.ValueMember = "value";
                if (brandList.Count > 0) this.brandId.SelectedIndex = 0;
                #endregion

                #region 加载打印方式
                this.sendPrintWay.Items.Clear();
                var wayList = EnumHelper.EnumToList<GlobalEnumVars.SendPrintWay>();
                sendPrintWay.DataSource = wayList;
                sendPrintWay.DisplayMember = "description";
                sendPrintWay.ValueMember = "value";
                if (wayList.Count > 0) this.sendPrintWay.SelectedIndex = 0;
                #endregion

                #region 纸张宽度
                this.paperType.Items.Clear();
                var paperTypeList = EnumHelper.EnumToList<GlobalEnumVars.paperType>();
                paperType.DataSource = paperTypeList;
                paperType.DisplayMember = "description";
                paperType.ValueMember = "value";
                if (paperTypeList.Count > 0) this.paperType.SelectedIndex = 0;
                #endregion

                #region 商品范围
                this.retryCount.Items.Clear();
                var retryCountList = EnumHelper.EnumToList<GlobalEnumVars.RetryCount>();
                retryCount.DataSource = retryCountList;
                retryCount.DisplayMember = "description";
                retryCount.ValueMember = "value";
                if (retryCountList.Count > 0) this.retryCount.SelectedIndex = 0;
                #endregion

                #region 加载打印机连接方式
                this.printConnect.Items.Clear();
                var printConnectList = EnumHelper.EnumToList<GlobalEnumVars.printConnect>();
                printConnect.DataSource = printConnectList;
                printConnect.DisplayMember = "description";
                printConnect.ValueMember = "value";
                if (printConnectList.Count > 0) this.printConnect.SelectedIndex = 0;
                #endregion

                #region 加载打印机品牌
                if (printscheme.printerType == (int)GlobalEnumVars.printerType.Kitchen)
                {
                    this.spareSchemeId.Items.Clear();
                    var SchemeList = new List<corecmsprintscheme>();
                    var printscheme0 = new corecmsprintscheme();
                    printscheme0.id = 0;
                    printscheme0.printerName = "无";
                    SchemeList.Add(printscheme0);
                    var SchemeList1 = new corecmsprintschemeServices().AsQueryable()
                        .Where(p => p.printerType == (int)GlobalEnumVars.printerType.Kitchen
                        && p.id != printscheme.id).ToList();
                    SchemeList.AddRange(SchemeList1);
                    spareSchemeId.DataSource = SchemeList;
                    spareSchemeId.DisplayMember = "printerName";
                    spareSchemeId.ValueMember = "id";
                    if (SchemeList.Count > 0) this.spareSchemeId.SelectedIndex = 0;
                }
                else
                {
                    this.spareSchemeId.Enabled = false;
                }
                #endregion

                #region 加载打印机状态
                this.status.Items.Clear();
                var statusList = EnumHelper.EnumToList<GlobalEnumVars.PrinterStatus>();
                status.DataSource = statusList;
                status.DisplayMember = "description";
                status.ValueMember = "value";
                this.status.SelectedValue = GlobalEnumVars.PrinterStatus.Default;
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void DoCreate()
        {
            try
            {
                int printschemeId = new corecmsprintschemeServices().InsertReturnIdentity(printscheme);
                if (printschemeId > 0)
                {
                    printscheme.id = printschemeId;
                    ShowSuccessTip("新增成功");
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                else
                {
                    UIMessageBox.Show("新增失败", "提示", UIStyle.Red, UIMessageBoxButtons.OK);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void DoEdit()
        {
            try
            {
                if (new corecmsprintschemeServices().UpdateAsync(printscheme))
                {
                    var objIni = IniFiles.ReadIniData("SystemPara", "printscheme_id");
                    int printscheme_id = CommFunc.ConvertToInt32(objIni);
                    ShowSuccessTip("修改成功");
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                else
                {
                    UIMessageBox.Show("修改失败", "提示", UIStyle.Red, UIMessageBoxButtons.OK);
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        private void btnOk_Click(object sender, System.EventArgs e)
        {
            try
            {
                if (!CheckData()) return;
                int sSendPrintWay = CommFunc.ConvertToInt32(sendPrintWay.SelectedValue);
                if (sSendPrintWay == (int)GlobalEnumVars.SendPrintWay.Drive)
                    this.printerIP.Text = "127.0.0.1";
                printscheme.gearName = this.gearName.Text;
                printscheme.region = this.region.Text;
                printscheme.printerName = this.printerName.Text;
                printscheme.printerType = CommFunc.ConvertToInt32(printerType.SelectedValue);
                printscheme.printerIP = this.printerIP.Text;
                printscheme.brandId = CommFunc.ConvertToInt32(brandId.SelectedValue);
                printscheme.paperType = CommFunc.ConvertToInt32(paperType.SelectedValue);
                printscheme.sendPrintWay = CommFunc.ConvertToInt32(sendPrintWay.SelectedValue);
                printscheme.buzzingCount = this.buzzingCount.Value;
                printscheme.buzzingType = this.buzzingType.Value;
                printscheme.emptyRows = this.emptyRows.Value;
                printscheme.retryCount = CommFunc.ConvertToInt32(retryCount.SelectedValue);
                printscheme.printConnect = CommFunc.ConvertToInt32(printConnect.SelectedValue);
                printscheme.printPort = this.printPort.Text;
                printscheme.baudrate = CommFunc.ConvertToInt32(this.baudrate.Text);
                printscheme.spareSchemeId = CommFunc.ConvertToInt32(spareSchemeId.SelectedValue);
                printscheme.status = CommFunc.ConvertToInt32(status.SelectedValue);
                printscheme.address = this.address.Text;
                printscheme.linkPhone = this.linkPhone.Text;
                if (printscheme.id > 0)
                    DoEdit();
                else
                    DoCreate();
                SaveSchemeDetail();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void SaveSchemeDetail()
        {
            //var buttons = this.GetControls<UIMultiButtons>(true);
            var billtemplates = new corecmsprintbilltemplateServices().AsQueryable()
                .Where(p => p.paperType == printscheme.paperType).ToList();

            var schemeDetails = new corecmsprintschemedetailServices().QueryByPrintSchemeId(printscheme.id);
            foreach (var item in schemeDetails)
            {
                item.selectedFlag = false;
            }
            //foreach (UIMultiButtons button in buttons)
            {
                //int[] ids = button.SelectedButtonsInts;
                int[] ids = mbtBillTypes.SelectedButtonsInts;
                foreach (int id in ids)
                {
                    var schemeDetail = schemeDetails.Find(p => p.billtypeId == id);
                    if (schemeDetail != null)
                    {
                        schemeDetail.selectedFlag = true;
                    }
                    else
                    {
                        var newDetail = new corecmsprintschemedetail();
                        newDetail.selectedFlag = true;
                        newDetail.printSchemeId = printscheme.id;
                        newDetail.templateId = 0;
                        newDetail.billtypeId = id;
                        newDetail.printCount = 1;
                        newDetail.foodSort = 2;
                        newDetail.foodPackPrintType = 1;
                        var billtemplate = billtemplates.Find(p => p.billtypeId == id);
                        if (billtemplate != null) newDetail.templateId = billtemplate.id;
                        schemeDetails.Add(newDetail);
                    }
                }
            }
            new corecmsprintschemedetailServices().InsertOrUpdateAsync(schemeDetails);
        }

        
        private bool CheckData()
        {
            try
            {
                if (gearName.Text == null || gearName.Text == "")
                {
                    UIMessageBox.Show("请输入打印机别名", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (printerName.Text == null || printerName.Text == "")
                {
                    UIMessageBox.Show("请输入打印机名称", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (printerType.Text == null || printerType.Text == "")
                {
                    UIMessageBox.Show("请输入打印机类型", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if ((printerIP.Text == null || printerIP.Text == "")
                    && (sendPrintWay.SelectedValue.ObjToInt(0) == (int)GlobalEnumVars.SendPrintWay.Command))
                {
                    UIMessageBox.Show("请输入ip地址", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (brandId.Text == null || brandId.Text == "")
                {
                    UIMessageBox.Show("请输入品牌", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (paperType.Text == null || paperType.Text == "")
                {
                    UIMessageBox.Show("请输入纸张宽度", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (sendPrintWay.Text == null || sendPrintWay.Text == "")
                {
                    UIMessageBox.Show("请输入打印方式", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (buzzingCount.Text == null || buzzingCount.Text == "")
                {
                    UIMessageBox.Show("请输入蜂鸣次数", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (buzzingType.Text == null || buzzingType.Text == "")
                {
                    UIMessageBox.Show("请输入蜂鸣等级", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (emptyRows.Text == null || emptyRows.Text == "")
                {
                    UIMessageBox.Show("请输入走纸行数", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (retryCount.Text == null || retryCount.Text == "")
                {
                    UIMessageBox.Show("请输入重试次数", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (printConnect.Text == null || printConnect.Text == "")
                {
                    UIMessageBox.Show("请输入打印机连接方式", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }
        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void sendPrintWay_SelectedValueChanged(object sender, EventArgs e)
        {
            if (sendPrintWay.SelectedValue.ObjToInt(0) == (int)GlobalEnumVars.SendPrintWay.Command || sendPrintWay.SelectedValue.ObjToInt(0) == (int)GlobalEnumVars.SendPrintWay.KDS_Bestone)
            {
                printerName.DropDownStyle = UIDropDownStyle.DropDown;
                printerIP.Enabled = true;
            }
            else
            {
                printerName.DropDownStyle = UIDropDownStyle.DropDownList;
                printerIP.Enabled = false;
            }
        }

        private void printerType_SelectedValueChanged(object sender, EventArgs e)
        {
            //printscheme.printerType = printerType.SelectedValue.ObjToInt(1);
            if (printerType.Enabled) LoadBillType(printerType.SelectedValue.ObjToInt(1));
        }
    }
}
